﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bosphorus.Migrator.Dialect.Core;
using Bosphorus.Migrator.Implementation.MigrationCommand;
using Bosphorus.Migrator.Model;
using Bosphorus.Migrator.Core.MigrationCommand;

namespace Bosphorus.Migrator.Dialect.DummyImplementation
{
    public class TableDialect : AbstractDialect<ICommand<Table>>
    {
        private readonly IDialect<ICommand<Column>> columnDialect;

        public TableDialect(IDialect<ICommand<Column>> columnDialect)
        {
            this.columnDialect = columnDialect;
        }

        public override string Create(ICommand<Table> command)
        {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.AppendFormat("CREATE TABLE [{0}] (", command.Model.Name);
            stringBuilder.AppendLine();

            string columns = CreateColumns(command.SubCommands);
            stringBuilder.Append(columns);
            stringBuilder.AppendLine(")");

            return stringBuilder.ToString();
        }

        private string CreateColumns(IList<ICommand> subCommands)
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (ICommand subCommand in subCommands)
            {
                Column column = (Column) subCommand.Model;
                ICommand<Column> newTypedCommand = new CreateCommand<Column>(column);
                string subStatement = columnDialect.Create(newTypedCommand);
                stringBuilder.Append(subStatement);

                if (subCommand != subCommands.Last())
                    stringBuilder.AppendLine(",");
                else
                    stringBuilder.AppendLine();
            }
            return stringBuilder.ToString();
        }

        public override string Alter(ICommand<Table> command)
        {
            //string command = string.Format("Alter Table {0}", model.Name);
            //return command;
            return string.Empty;
        }

        public override string Drop(ICommand<Table> command)
        {
            string commandStrging = string.Format("DROP TABLE {0}", command.Model.Name);
            return commandStrging;
        }
    }
}
